package com.atguigu.tingshu.search.service.impl;

import com.atguigu.tingshu.album.client.AlbumClientFeign;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.util.PinYinUtils;
import com.atguigu.tingshu.model.album.AlbumAttributeValue;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.BaseCategoryView;
import com.atguigu.tingshu.model.search.AlbumInfoIndex;
import com.atguigu.tingshu.model.search.AttributeValueIndex;
import com.atguigu.tingshu.model.search.SuggestIndex;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.search.dao.AlbumInfoDao;
import com.atguigu.tingshu.search.dao.SuggestIndexDao;
import com.atguigu.tingshu.search.service.ItemService;
import com.atguigu.tingshu.user.client.UserClientFeign;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.elasticsearch.core.suggest.Completion;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/***
 * es的写操作的服务接口类的实现类
 */
@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
@AllArgsConstructor
public class ItemServiceImpl implements ItemService {

    private AlbumInfoDao albumInfoDao;

    private SuggestIndexDao suggestIndexDao;

    private AlbumClientFeign albumClientFeign;

    private UserClientFeign userClientFeign;

    /**
     * 专辑写入es
     *
     * @param albumId 专辑id
     */
    @Override
    public void addAlbumFromMysqlToEs(Long albumId) {
        // 去专辑微服务查询专辑信息
        AlbumInfo albumInfo = albumClientFeign.getAlbumInfo(albumId);
        // 如果没有专辑信息 直接返回
        if (albumInfo == null || albumInfo.getId() == null) {
            return;
        }
        // 初始化es实体
        AlbumInfoIndex albumInfoIndex = new AlbumInfoIndex();
        // 查询es中是否存在这个专辑
        Optional<AlbumInfoIndex> optional = albumInfoDao.findById(albumId);
        if (optional.isPresent()) {
            // 存在
            albumInfoIndex = optional.get();
        }
        // 设置属性：id 专辑标题 专辑简介
        albumInfoIndex.setId(albumInfo.getId());
        albumInfoIndex.setAlbumTitle(albumInfo.getAlbumTitle());
        albumInfoIndex.setAlbumIntro(albumInfo.getAlbumIntro());

        // 去用户微服务查询用户信息
        UserInfo userInfo = userClientFeign.getUserInfo(albumInfo.getUserId());
        albumInfoIndex.setAnnouncerName(userInfo.getNickname());
        albumInfoIndex.setCoverUrl(albumInfo.getCoverUrl());
        albumInfoIndex.setIncludeTrackCount(albumInfo.getIncludeTrackCount());
        albumInfoIndex.setIsFinished(albumInfo.getIsFinished().shortValue());
        albumInfoIndex.setPayType(albumInfo.getPayType());
        albumInfoIndex.setCreateTime(new Date());

        // 根据三级分类查询一级二级三级分类
        BaseCategoryView baseCategoryView = albumClientFeign.getBaseCategoryView(albumInfo.getCategory3Id());
        albumInfoIndex.setCategory1Id(baseCategoryView.getCategory1Id());
        albumInfoIndex.setCategory2Id(baseCategoryView.getCategory2Id());
        albumInfoIndex.setCategory3Id(baseCategoryView.getCategory3Id());

        // 专辑的标签数据
        List<AlbumAttributeValue> albumAttributeValueList = albumClientFeign.getAlbumAttributeValueList(albumId);
        albumInfoIndex.setAttributeValueIndexList(
                albumAttributeValueList.stream().map(albumAttributeValue -> {
                    // es的实体
                    AttributeValueIndex attributeValueIndex = new AttributeValueIndex();
                    attributeValueIndex.setAttributeId(albumAttributeValue.getAttributeId());
                    attributeValueIndex.setValueId(albumAttributeValue.getValueId());
                    // 返回
                    return attributeValueIndex;
                }).collect(Collectors.toList())
        );

        // 查询专辑的统计信息
        Map<String, Object> albumStatMap = albumClientFeign.getAlbumStatMap(albumId);
        albumInfoIndex.setPlayStatNum(Long.valueOf(albumStatMap.get(SystemConstant.ALBUM_STAT_PLAY).toString()));
        albumInfoIndex.setSubscribeStatNum(Long.valueOf(albumStatMap.get(SystemConstant.ALBUM_STAT_SUBSCRIBE).toString()));
        albumInfoIndex.setBuyStatNum(Long.valueOf(albumStatMap.get(SystemConstant.ALBUM_STAT_BROWSE).toString()));
        albumInfoIndex.setCommentStatNum(Long.valueOf(albumStatMap.get(SystemConstant.ALBUM_STAT_COMMENT).toString()));
        // 保存
        albumInfoDao.save(albumInfoIndex);

        // 专辑标题提示词写入es
        saveSuggestIndex(albumInfoIndex.getAlbumTitle(), albumInfoIndex.getAlbumTitle());
        // 专辑简介提示词写入es
        saveSuggestIndex(albumInfoIndex.getAlbumIntro(), albumInfoIndex.getAlbumTitle());
        // 专辑作者提示词写入es
        saveSuggestIndex(albumInfoIndex.getAnnouncerName(), albumInfoIndex.getAnnouncerName());
    }

    /**
     * 专辑从es删除
     *
     * @param albumId 专辑id
     */
    @Override
    public void removeFromEs(Long albumId) {
        albumInfoDao.deleteById(albumId);
    }

    /**
     * 提示词初始化
     *
     * @param suggestInfo1 提示词1
     * @param suggestInfo2 提示词2
     */
    private void saveSuggestIndex(String suggestInfo1, String suggestInfo2) {
        // 初始化
        SuggestIndex suggestIndex = new SuggestIndex();
        // 补全属性
        suggestIndex.setId(UUID.randomUUID().toString().replace("-", ""));
        suggestIndex.setTitle(suggestInfo2);
        suggestIndex.setKeyword(new Completion(new String[]{suggestInfo1}));
        suggestIndex.setKeywordPinyin(new Completion(new String[]{PinYinUtils.toHanyuPinyin(suggestInfo1)}));
        suggestIndex.setKeywordSequence(new Completion(new String[]{PinYinUtils.getFirstLetter(suggestInfo1)}));
        // 保存提示词
        suggestIndexDao.save(suggestIndex);
    }
}
